#include "CTextureManager.h"
#include <cstring>
#include <windows.h>
#include "gltools.h"
#include "TGALoader.h"
//#include "glpng.h"
#pragma warning(disable:4996)

CTextureManager::CTextureManager()
{
}

CTextureManager *CTextureManager::GetInstance()
{
	static CTextureManager Instance;
	return &Instance;
}

Texture *CTextureManager::LoadTexture(char *szFile)
{
	for (unsigned int i = 0; i < m_vTextureList.size(); i++)
	{
		if (!stricmp(szFile, m_vTextureList[i]->m_szFile))
			return m_vTextureList[i];
	}

	Texture *pTex = new Texture;
	strcpy(pTex->m_szFile, szFile);
	
	glGenTextures(1, &pTex->m_unHandle);
	glBindTexture(GL_TEXTURE_2D, pTex->m_unHandle);
	float maxAnio;
	glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnio);
	glTexParameterf(GL_TEXTURE_2D, GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, maxAnio);

	LoadTGA(szFile, pTex->m_nHeight, pTex->m_nWidth);
	//pngInfo tempInfo;
	//int nSuccess = pngLoad(szFile, PNG_BUILDMIPMAPS, PNG_ALPHA, &tempInfo);
	//pTex->m_nHeight = tempInfo.Height;
	//pTex->m_nWidth = tempInfo.Width;
	
	m_vTextureList.push_back(pTex);
	return pTex;
}

Texture *CTextureManager::LoadTextureFromMemory(char *szFileName, char *pData)
{
	for (unsigned int i = 0; i < m_vTextureList.size(); i++)
	{
		if (!stricmp(szFileName, m_vTextureList[i]->m_szFile))
			return m_vTextureList[i];
	}

	Texture *pTex = new Texture;
	strcpy(pTex->m_szFile, szFileName);
	
	glGenTextures(1, &pTex->m_unHandle);
	glBindTexture(GL_TEXTURE_2D, pTex->m_unHandle);

	LoadTGAFromMemory(pData, pTex->m_nHeight, pTex->m_nWidth);
	//pngInfo tempInfo;
	//pngLoadF((FILE *)pData, PNG_BUILDMIPMAPS, PNG_ALPHA, &tempInfo);
	////int nSuccess = pngLoad(szFile, PNG_BUILDMIPMAPS, PNG_ALPHA, &tempInfo);
	//pTex->m_nHeight = tempInfo.Height;
	//pTex->m_nWidth = tempInfo.Width;
	
	m_vTextureList.push_back(pTex);
	return pTex;
}

void CTextureManager::ReleaseAll()
{
	while (m_vTextureList.size())
	{
		glDeleteTextures(1, &m_vTextureList[0]->m_unHandle);
		delete m_vTextureList[0];
		m_vTextureList.erase(m_vTextureList.begin());
	}
}